package blog

import (
	"ginblog/api/common"
	"ginblog/model"
	"ginblog/tools/jwt"
	gin "github.com/gin-gonic/gin"
)

type LoginV1 struct {
	common.LoginBase
}

// DoLogin /** 登陆主入口
func (Login *LoginV1) DoLogin(c *gin.Context) {
	//用户密码不能为空
	if !Login.IsSetPassword() {
		Login.LoginFail(c)
		return
	}
	Blog := model.Blog{}
	//是否是手机号登陆
	if Login.IsSetPhone() {
		Blog.Phone = Login.Phone
		Login.QueryLogin(c, &Blog)
		return
	}
	//是否是邮箱登陆
	if Login.IsSetEmail() {
		Blog.Email = Login.Email
		Login.QueryLogin(c, &Blog)
		return
	}
	//是否是用户名登陆
	if Login.IsSetUserName() {
		Blog.UserName = Login.UserName
		Login.QueryLogin(c, &Blog)
		return
	}
	Login.LoginFail(c)
}

// QueryLogin /** 查询登陆
func (Login *LoginV1) QueryLogin(c *gin.Context, b *model.Blog) {
	err := model.Db.Where(b).First(b).Error
	if err != nil {
		Login.LoginFail(c)
		return
	}
	if !b.ExaminePassWord(b.PassWordEncrypt(Login.Password)) {
		Login.LoginFail(c)
		return
	}
	flag, token := jwt.SetToken(c, b)
	if !flag {
		Login.LoginFail(c)
		return
	}
	data := map[string]string{
		"token":        token,
		"username":     b.UserName,
		"usericon":     b.UserIcon,
		"email":        b.Email,
		"friend_chain": b.FriendChain,
	}
	Login.LoginSuccess(c, data)
	return
}
